import React from 'react';
import ReactDOM from 'react-dom';

import AppReactRedux from './AppReactRedux';
import {Provider} from 'react-redux';
import {createStore} from 'redux';

function counter(state=0,action){
    switch(action.type){
        case 'INCREMENT':
            return state+1;
        case 'DECREMENT':
            return state-1;
            default:
                return state
    }
}
const store=createStore(counter)
ReactDOM.render(
    <Provider store={store}>
        <AppReactRedux />
    </Provider>, 
    document.getElementById('root')
);



/*
//导入redux模块，creareStore用来创建状态存储库
import {createStore} from 'redux';
//声明一个redux函数，用来接受state状态和action动作，然后进行处理，返回新的数据
function counter(state=0,action){
    switch(action.type){
        case 'INCREMENT':return state+1;
        case 'DECREMENT':return state-1;
        default:return state;
    }
}
//creareStore用来创建状态存储库，需要接收一个runder函数
const store=createStore(counter);
//订阅状态变化，在store里的状态变化后调用回调函数
store.subscribe(function(){
    //返回状态存储库store里的最新状态
    console.log(store.getState())
})

store.dispatch({type:'INCREMENT'})
store.dispatch({type:'DECREMENT'})

function exist(items,product_id){
    for(let i=0;i<items.length;i++){
        let item=items[i];
        if(item.id===product_id){
            return{i,item}
        }
    }
    return false;
}


function produceReducer(state={products:[],shoppingCar:{items:[]}},action){
    switch(action.type){
        case 'ADD_PRODUCT'://添加商品
            return{...state,products:[...state.products,action.product]};
        case 'PICK_PRODUCT'://推荐到购物车
            let items=state.shoppingCar.items;
            let product=action.product;
            let newItems=[...items];
            let itemObj=exist(newItems,product.id);
            if(itemObj){
                console.log(itemObj)
                newItems[itemObj.i]={...itemObj.item,count:itemObj.item.count+1}
            }else{
                newItems.push({...product,count:1})
            }

            return{...state,shoppingCar:{items:newItems}}
            default:
                return state
    }
}


const store1=createStore(produceReducer);
store1.subscribe(function(){
    console.log(store1.getState())
})

store1.dispatch({type:'ADD_PRODUCT',product:{id:'001',name:'🐖'}})
store1.dispatch({type:'ADD_PRODUCT',product:{id:'002',name:'🐇'}})
store1.dispatch({type:'ADD_PRODUCT',product:{id:'003',name:'🐓'}})

store1.dispatch({type:'PICK_PRODUCT',product:{id:'003',name:'🐓'}})
store1.dispatch({type:'PICK_PRODUCT',product:{id:'003',name:'🐓'}})
store1.dispatch({type:'PICK_PRODUCT',product:{id:'001',name:'🐖'}})*/